package com.pivotal.cloud.security.password;

import com.pivotal.cloud.crypto.codec.Utf8;
import com.pivotal.cloud.crypto.keygen.BytesKeyGenerator;
import com.pivotal.cloud.crypto.keygen.KeyGenerators;
import com.pivotal.cloud.crypto.utils.EncodingUtil;

import java.security.MessageDigest;
import java.util.Base64;
import java.util.Locale;

/**
 * @className: LdapShaPasswordEncoder
 * @projectName: PivotalCloud项目
 * @module: PivotalCloud项目-LdapShaPasswordEncoder类，主要位于Security安全模块-LdapSha模式密码加密模块
 * @content: LdapShaPasswordEncoder-LdapSha模式密码加密
 * @author: Powered by Marklin
 * @datetime: 2025-06-24 13:34
 * @version: 1.0.0
 * @copyright: Copyright © 2018-2025 PivotalCloud Systems Incorporated. All rights
 * reserved.
 */
public class LdapShaPasswordEncoder implements PasswordEncoder {

	/**
	 * The number of bytes in a SHA hash
	 */
	private static final int SHA_LENGTH = 20;

	private static final String SSHA_PREFIX = "{SSHA}";

	private static final String SSHA_PREFIX_LC = SSHA_PREFIX.toLowerCase(Locale.ENGLISH);

	private static final String SHA_PREFIX = "{SHA}";

	private static final String SHA_PREFIX_LC = SHA_PREFIX.toLowerCase(Locale.ENGLISH);

	private final BytesKeyGenerator saltGenerator;

	private boolean forceLowerCasePrefix;

	public LdapShaPasswordEncoder() {
		this(KeyGenerators.secureRandom());
	}

	public LdapShaPasswordEncoder(BytesKeyGenerator saltGenerator) {
		if (saltGenerator == null) {
			throw new IllegalArgumentException("saltGenerator cannot be null");
		}
		this.saltGenerator = saltGenerator;
	}

	private byte[] combineHashAndSalt(byte[] hash, byte[] salt) {
		if (salt == null) {
			return hash;
		}
		byte[] hashAndSalt = new byte[hash.length + salt.length];
		System.arraycopy(hash, 0, hashAndSalt, 0, hash.length);
		System.arraycopy(salt, 0, hashAndSalt, hash.length, salt.length);
		return hashAndSalt;
	}

	/**
	 * 实例化对象
	 */
	private static final PasswordEncoder INSTANCE = LdapShaPasswordEncoder.newInstance();

	/**
	 * 获取实例
	 * @return 返回结果
	 */
	public static PasswordEncoder getInstance() {
		return INSTANCE;
	}

	/**
	 * 实例化对象
	 * @return 返回结果
	 */
	public static PasswordEncoder newInstance() {
		return new LdapShaPasswordEncoder();
	}

	/**
	 * 密码加密
	 * @param rawPassword 原始密码
	 * @return 返回结果
	 */
	@Override
	public String encode(CharSequence rawPassword) {
		byte[] salt = this.saltGenerator.generateKey();
		return encode(rawPassword, salt);
	}

	private String encode(CharSequence rawPassword, byte[] salt) {
		MessageDigest sha = getSha(rawPassword);
		if (salt != null) {
			sha.update(salt);
		}
		byte[] hash = combineHashAndSalt(sha.digest(), salt);
		String prefix = getPrefix(salt);
		return prefix + Utf8.decode(Base64.getEncoder().encode(hash));
	}

	private MessageDigest getSha(CharSequence rawPassword) {
		try {
			MessageDigest sha = MessageDigest.getInstance("SHA");
			sha.update(Utf8.encode(rawPassword));
			return sha;
		}
		catch (java.security.NoSuchAlgorithmException ex) {
			throw new IllegalStateException("No SHA implementation available!");
		}
	}

	private String getPrefix(byte[] salt) {
		if (salt == null || salt.length == 0) {
			return this.forceLowerCasePrefix ? SHA_PREFIX_LC : SHA_PREFIX;
		}
		return this.forceLowerCasePrefix ? SSHA_PREFIX_LC : SSHA_PREFIX;
	}

	private byte[] extractSalt(String encPass) {
		String encPassNoLabel = encPass.substring(6);
		byte[] hashAndSalt = Base64.getDecoder().decode(encPassNoLabel.getBytes());
		int saltLength = hashAndSalt.length - SHA_LENGTH;
		byte[] salt = new byte[saltLength];
		System.arraycopy(hashAndSalt, SHA_LENGTH, salt, 0, saltLength);
		return salt;
	}

	/**
	 * 验证密码
	 * @param rawPassword 原始密码
	 * @param encodedPassword 加密密码
	 * @return 返回结果
	 */
	@Override
	public boolean matches(CharSequence rawPassword, String encodedPassword) {
		return matches((rawPassword != null) ? rawPassword.toString() : null, encodedPassword);
	}

	private boolean matches(String rawPassword, String encodedPassword) {
		String prefix = extractPrefix(encodedPassword);
		if (prefix == null) {
			return EncodingUtil.equals(encodedPassword, rawPassword);
		}
		byte[] salt = getSalt(encodedPassword, prefix);
		int startOfHash = prefix.length();
		String encodedRawPass = encode(rawPassword, salt).substring(startOfHash);
		return EncodingUtil.equals(encodedRawPass, encodedPassword.substring(startOfHash));
	}

	private byte[] getSalt(String encodedPassword, String prefix) {
		if (prefix.equals(SSHA_PREFIX) || prefix.equals(SSHA_PREFIX_LC)) {
			return extractSalt(encodedPassword);
		}
		if (!prefix.equals(SHA_PREFIX) && !prefix.equals(SHA_PREFIX_LC)) {
			throw new IllegalArgumentException("Unsupported password prefix '" + prefix + "'");
		}
		// Standard SHA
		return null;
	}

	/**
	 * Returns the hash prefix or null if there isn't one.
	 */
	private String extractPrefix(String encPass) {
		if (!encPass.startsWith("{")) {
			return null;
		}
		int secondBrace = encPass.lastIndexOf('}');
		if (secondBrace < 0) {
			throw new IllegalArgumentException("Couldn't find closing brace for SHA prefix");
		}
		return encPass.substring(0, secondBrace + 1);
	}

	public void setForceLowerCasePrefix(boolean forceLowerCasePrefix) {
		this.forceLowerCasePrefix = forceLowerCasePrefix;
	}

}
